<?php

namespace App\Http\Controllers;

use App\Models\Sns;
use App\Models\SnsPic;
use App\Models\SnsVideo;
use Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;
use zgldh\QiniuStorage\QiniuStorage;
use Illuminate\Http\Request;
use PhpParser\Error;

class UploadController extends Controller
{
  // 上传图片
  public function imgUpload(Request $request)
  {
    $file = Input::file('file');
    $allowedExtensions = ["png", "jpg", "jpeg", "svg"];
    if ($file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(), $allowedExtensions)) {
      return $this->failure(-1, '只允许上传 png jpg jpeg svg 格式的图片');
    }
    $destinationPath = 'uploads/images/';
    $extension = $file->getClientOriginalExtension();
    $fileName = time().str_random(1) . '.' . $extension;
    $file->move($destinationPath, $fileName);
    $data['image_name'] = $fileName;
    $data['img_url'] = asset($destinationPath . $fileName);
    return $this->success(0, '上传成功', $data);
  }

  // 上传视频
  public function videoUpload(Request $request)
  {
    if($request->hasFile('file')) {
      $file = Input::file('file');
      $extension = $file->getClientOriginalExtension();
      $filename = time().str_random(1) . '.' . $extension;
      $destinationPath = 'uploads/videos/';
      $file->move($destinationPath, $filename);
      $data['video_name'] = $filename;
      $data['video_url'] = asset($destinationPath . $filename);

      return $this->success(0, '上传成功', $data);
    }
    return $this->failure(-1, '没有上传任何文件');
  }

  public function imgDelete(Request $request)
  {
    if($request->id){
        SnsPic::where('id',$request->id)->delete();
    }
    $destinationPath = 'uploads/images/';
    $path = public_path() . '/' . $destinationPath . $request->name;
    $rs = \File::delete($path);
    if($rs) {
      return $this->success(0);
    }
    return $this->failure(-1);
  }

  public function videoDelete(Request $request)
  {
      if($request->id){
          SnsVideo::where('id',$request->id)->delete();
          Sns::where('sns_video_id',$request->id)->update(['sns_video_id' => null]);
      }
    $destinationPath = 'uploads/videos/';
    $path = public_path() . '/' . $destinationPath . $request->video_name;
    $rs = \File::delete($path);
    if($rs) {
      return $this->success(0);
    }
    return $this->failure(-1);
  }

  public function tmpImgDelete(Request $request)
  {
    $validator = Validator::make($request->all(), [
      'image_name' => 'required|string',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $image_name = $request->image_name;
    $destinationPath = 'uploads/images/';
    $convertDir = $destinationPath . 'converts/';
    $path = public_path() . '/' . $convertDir . $image_name;
    $rs = \File::delete($path);
    if($rs) {
      return $this->success(0);
    }
    return $this->failure(-1);
  }
}
